<!-- 文件读取 -->
<template>
  <div>
    <div class="part part-1">
      <h3>FileReader读取文件</h3>
      <input type="file" ref="file">
      <br>
      <el-button size="mini" @click="readAsText('txt')">读取为txt</el-button>
      <el-button size="mini" @click="readAsText('ArrayBuffer')">读取为ArrayBuffer</el-button>
      <el-button size="mini" @click="readAsText('DataURL')">读取为DataURL</el-button>
      <el-button size="mini" @click="readAsText('BinaryString')">读取为BinaryString</el-button>
      <br>
      <p>阅读结果展示：</p>
      <div class="content">
        {{content}}
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "index",
    data() {
      return {
        content: ''
      }
    },
    methods: {
      readAsText(type) {
        debugger
        const file = this.$refs.file.files[0]; // 获取上传的文件对象
        const reader = new FileReader(); // 生成文件阅读器
        switch (type) {
          case 'txt':
            reader.readAsText(file, 'utf-8'); // 以utf-8格式阅读，输出文本格式内容，默认utf-8
            break;
          case 'DataURL':
            reader.readAsDataURL(file);
            break;
          case 'BinaryString':
            reader.readAsBinaryString(file)
            break;
          case 'ArrayBuffer':
            reader.readAsArrayBuffer(file)
            break;
        }
        this.content = ''; // 用一个变量接收文件阅读器解析出来的内容
        reader.onload =  (result) => { // 需要在onload-读取中进行处理
          this.content = reader.result; // FileReader是直接读取整个文件的
        }
      }
    }
  }
</script>

<style scoped>
.content{
  min-height: 200px;
  border: 1px solid;
}
</style>
